package com.web.cms.doc.dao;

import com.blue.jdbc.BaseDao;
import com.web.cms.doc.model.DocFile;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Repository("cmsDocFileDao")
public class DocFileDao extends BaseDao<DocFile>
{
	public DocFileDao()
	{
	}

	@Override
	protected void query(StringBuilder sql, DocFile param)
	{
		if (param != null)
		{
			if (param.getDocId() != null && param.getDocId() > 0)
				sql.append(" and a.doc_id=:docId");

			if (param.getWebId() != null && param.getWebId() > 0)
				sql.append(" and a.web_id=:webId");

			if (param.getType() != null)
				sql.append(" and a.type=:type");
			
			if (param.getPos() != null)
				sql.append(" and a.pos=:pos");

		}
		sql.append(" order by a.id desc");
	}

	@Override
	protected StringBuilder select()
	{
		StringBuilder sql = new StringBuilder(64);
		sql.append("select a.*, d.title doc_title, w.name web_name from cms_doc_file a");
		sql.append(" left join cms_doc d on d.id=a.doc_id");
		sql.append(" left join cms_web w on w.id=a.web_id");
		sql.append(" where 1=1");
		return sql;
	}

	public List<Integer> listIdByKey(List<String> keyList)
	{
		if (keyList == null || keyList.isEmpty())
			return new ArrayList<>();

		String sql = String.format("select id from cms_doc_file where `key` in (%s)",
				StringUtils.repeat("?", ",", keyList.size()));
		return jdbcTemplate.queryForList(sql, Integer.class, keyList.toArray());
	}

	public void setDocId(Integer docId, Collection<Integer> idList)
	{
		if (idList == null || idList.isEmpty())
			return;

		String sql = String.format("update cms_doc_file set doc_id=? where id in (%s)", StringUtils.join(idList, ","));
		jdbcTemplate.update(sql, docId);
		
		sql = "update cms_doc d, (select count(*) n, ifnull(sum(size), 0) size from cms_doc_file where doc_id=?) f set d.files=f.n, d.file_size=f.size where d.id=?";
		jdbcTemplate.update(sql, docId, docId);
	}

	public void setDocId(Integer docId)
	{
		if (docId == null)
			return;

		String sql = "update cms_doc_file set doc_id=null where doc_id=?";
		jdbcTemplate.update(sql, docId);
	}

}
